/*
 * Copyright (c)  2016, newtouch.com
 * All rights reserved.
 * AccessTokenServiceImpl.java 2016-10-22 下午4:47
 */
package com.xiqing.wechat.service.token.impl;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiqing.wechat.entity.token.AccessToken;
import com.xiqing.wechat.entity.token.JsApiInfo;
import com.xiqing.wechat.entity.token.Ticket;
import com.xiqing.wechat.service.token.AccessTokenService;
import com.xiqing.wechat.web.util.HttpsKit;
import com.xiqing.wechat.web.util.JsApiSign;
import com.xiqing.wechat.web.util.WeiXinURL;
import io.dabing.core.service.AbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：TODO
 *
 * @author wanglijun create on 2016-10-22
 * @since 1.0
 */
@Service
public class AccessTokenServiceImpl extends AbstractService implements AccessTokenService {

    /**日志*/
    private static final Logger logger= LoggerFactory.getLogger (AccessTokenServiceImpl.class);

    /**微信APPID－用户唯一凭证*/
    private String appId="wx2d4ff8b7fac19195";
    /**微信 weixin.appsecret 唯一凭证密钥*/
    private String appSecret="a3f7a9816151e4454e24391edbb522bc";

    private static AccessToken accessTokenObj;

    private static Ticket ticket;


    public String getAccessToken() {

        if(accessTokenObj!=null&&accessTokenObj.getExpiredDate ().after (new Date())){
            return accessTokenObj.getAccessToken ();
        }

        Map<String,String> params=new HashMap<String,String> ();
        params.put("appid",appId);
        params.put("secret",appSecret);
        String result= HttpsKit.execute(WeiXinURL.ACCESS_TOKEN_URL.URL(),params);
        log.info("result:{}",result);
        Map<String, Object> map = JSONObject.parseObject(result);
        String accessToken=map.get("access_token").toString();
        Integer expiresIn=(Integer) map.get("expires_in");
        log.info("accessToken:{},expiresIn:{}",accessToken,expiresIn);

        //加载日期
        Calendar calendar=Calendar.getInstance ();
        calendar.setTime (new Date ());
        calendar.add (Calendar.SECOND,expiresIn);

        accessTokenObj=new AccessToken ();
        accessTokenObj.setAccessToken (accessToken);
        accessTokenObj.setExpireSecond (expiresIn);
        accessTokenObj.setExpiredDate (calendar.getTime ());

        return  accessToken;
    }

    public JsApiInfo getJsTicket(String url) {

        String ticket = getJsApiTicket();
        Map<String, String> map = JsApiSign.sign(ticket, url);
        if (null != map) {
            JsApiInfo info = new JsApiInfo();
            info.setAppId(appId);
            info.setNonceStr(map.get("nonceStr"));
            info.setTimestamp(map.get("timestamp"));
            info.setSignature(map.get("signature"));

            return info;
        }
        return null;
    }

    public String getJsApiTicket() {

        if(ticket!=null&&ticket.getExpiredDate ().after (new Date ())){
            return ticket.getTicket ();
        }

        String url ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+this.getAccessToken ()+"&type=jsapi";
        try {
            String json = HttpsKit.execute (url,null);

            logger.info ("json:{}",json);

            if (!StringUtils.isEmpty(json) && json.indexOf("ticket") >= 0) {
                JSONObject jsonObject=JSON.parseObject (json);

                String  ticketStr=jsonObject.getString("ticket");

                Integer  expiresIn=jsonObject.getInteger ("expires_in");


                //加载日期
                Calendar calendar=Calendar.getInstance ();
                calendar.setTime (new Date ());
                calendar.add (Calendar.SECOND,expiresIn);

                ticket=new Ticket ();
                ticket.setExpiredDate (calendar.getTime ());
                ticket.setExpiesIn (expiresIn);
                ticket.setTicket (ticketStr);
                return ticket.getTicket ();

            }
        } catch (Exception ex) {

        }
        return "";
    }
}
